package it.valeandre.omino.adapter;

import it.valeandre.omino.R;
import it.valeandre.omino.image.ImageDownloadService;
import it.valeandre.omino.image.ImageDownloadServiceListener;
import it.valeandre.omino.model.Item;
import it.valeandre.omino.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

public class FeedsAdapter extends BaseAdapter implements ListAdapter {

	private LayoutInflater mInflater;
	private ArrayList<Item> mFeeds;
	protected HashMap<String, Bitmap> mImageCache = new HashMap<String, Bitmap>();
	protected Handler mHandler = new Handler();
	private Context mContext;

	public FeedsAdapter(ArrayList<Item> feeds, Context context) {
		mContext = context;
		mFeeds = feeds;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public void setData(ArrayList<Item> feeds) {
		mFeeds = feeds;
		notifyDataSetChanged();
	}

	public int getCount() {
		return mFeeds.size();
	}

	public Item getItem(int pos) {
		return mFeeds.get(pos);
	}

	public long getItemId(int pos) {
		return pos;
	}
	
	private boolean isItemValid(Item item) {
		return item != null && item.getEnclosure() != null && item.getEnclosure().getUrl() != null && item.getEnclosure().getUrl().length() > 0;
	}

	public View getView(int position, View convertView, ViewGroup adapterView) {
		View view = convertView;
		if (view == null) {
			view = mInflater.inflate(R.layout.feeds_item, null);
		}
		Item item = getItem(position);

		ImageView image = (ImageView) view.findViewById(R.id.feed_item_picture);
//		image.setTag(Integer.valueOf(position));
		image.setTag("" + position);
		TextView date = (TextView) view.findViewById(R.id.feed_item_date);
		TextView title = (TextView) view.findViewById(R.id.feed_item_title);

//		String dateString = Utils.convertLocale(item.getPubDate(), Locale.UK, Locale.ITALIAN, "EEE, dd MMM yyyy hh:mm:ss z", "EEE, dd MMM yyyy");
//		date.setText(dateString);
		date.setText(item.getPubDate());
		title.setText(item.title);

		if (mImageCache != null && isItemValid(item) && mImageCache.containsKey(item.getEnclosure().getUrl()) && mImageCache.get(item.getEnclosure().getUrl()) != null && !mImageCache.get(item.getEnclosure().getUrl()).isRecycled()) {
			image.setImageBitmap(mImageCache.get(item.getEnclosure().getUrl()));
		} else {
			image.setImageResource(R.drawable.clipping_picture);
			downloadImage(item.getEnclosure().getUrl(), position, image);

		}
		return view;
	}

	private void downloadImage(final String url, final int position, final ImageView image) {
		
		ImageDownloadService.getInstance().downloadImage(mContext, url, new ImageDownloadServiceListener() {

			@Override
			public void downloadImagePerformed(final String url, final String filename) {

				mHandler.post(new Runnable() {
					public void run() {
						
//						if (((Integer) image.getTag()).intValue() == position) {
						if (image.getTag().equals("" + position)) {
							BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 1;
							float density = Utils.getDisplayDensity((Activity) mContext);
							if (density == DisplayMetrics.DENSITY_MEDIUM) {
								options.inSampleSize = 2;
							} else {
								options.inSampleSize = 1;
							}
							final Bitmap bitmap = BitmapFactory.decodeFile(filename, options);
							mImageCache.put(url, bitmap);
							image.setImageBitmap(bitmap);
							Animation myFadeInAnimation = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);
							myFadeInAnimation.setAnimationListener(new AnimationListener() {
								
								public void onAnimationStart(Animation animation) {
									image.setVisibility(View.VISIBLE);
								}
								
								public void onAnimationRepeat(Animation animation) {
								}
								
								public void onAnimationEnd(Animation animation) {
								}
							});
							image.startAnimation(myFadeInAnimation);
						}
					}
				});
			}

			@Override
			public void downloadImageFailed(String url, int statusCode) {
			}

			@Override
			public void downloadImageFailed(String url, Throwable reason) {
				reason.printStackTrace();
			}

		});
	}

	@Override
	public boolean areAllItemsEnabled() {
		return true;
	}

	@Override
	public int getViewTypeCount() {
		return 1;
	}

	public void recycle() {
		for (Bitmap bitmap : mImageCache.values()) {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}

		mImageCache.clear();
	}
	
	public void reset() {
		recycle();
	}

}
